package org.kl.bpm.operation;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.kl.bf.web.base.BasicController;
import org.kl.bpm.entity.conf.BpmKvProp;
import org.kl.bpm.entity.conf.BpmKvRecord;

public class RecordBuilder {
	public static final int process_cache_data = 0;// 默认为0(流程缓存数据)
	public static final int user_task_data = 1;// 1（任务表单数据）

	public BpmKvRecord build(BpmKvRecord record, int status, Map<String, String[]> parameters) {
		record.setStatus(status);
		Set<BpmKvProp> propSet = new HashSet<BpmKvProp>();
		for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
			String key = entry.getKey();
			String[] value = entry.getValue();
			if ((value == null) || (value.length == 0)) {
				continue;
			}
			BpmKvProp prop = getBpmKvProp(key, record);
			prop.setCode(key);
			prop.setType(RecordBuilder.process_cache_data);
			prop.setValue(this.getValue(value));
			prop.setBpmKvRecord(record);
			record.getProps().put(prop.getCode(), prop);
			propSet.add(prop);
			
		}
		record.setBpmKvProps(propSet);
		return record;
	}

	public BpmKvRecord build(String category, int status, Map<String, String[]> parameters) {
		BpmKvRecord record = new BpmKvRecord();
		record.setCategory(category);
		return build(record, status, parameters);
	}

	@SuppressWarnings("unchecked")
	public BpmKvRecord build(BpmKvRecord record, int status, String ref) {
		record.setRef(ref);
		return build(record, status, Collections.EMPTY_MAP);
	}

	private BpmKvProp getBpmKvProp(String key, BpmKvRecord record) {
		BpmKvProp emptyBKP = new BpmKvProp();
		emptyBKP.setCreateBy(BasicController.getCurrentUserId());
		emptyBKP.setCreateTime(new Timestamp(System.currentTimeMillis()));
		emptyBKP.setCreateDept(BasicController.getCurrentUserDeptId());
		return emptyBKP;
	}

	public String getValue(String[] values) {
		if ((values == null) || (values.length == 0)) {
			return "";
		}
		if (values.length == 1) {
			return values[0];
		}
		StringBuilder buff = new StringBuilder();
		for (String value : values) {
			buff.append(value).append(",");
		}
		buff.deleteCharAt(buff.length() - 1);
		return buff.toString();
	}
}
